//
//  HomeTableViewCell.swift
//  CXDownload_Example
//
//  Created by chenxing on 2023/7/10.
//  Copyright © 2023 CocoaPods. All rights reserved.
//

import UIKit

class MYGCloudDiskUploadDownloadCell: UITableViewCell {
    @IBOutlet weak var progressView: UIProgressView!
    
    @IBOutlet weak var statusLB: UILabel!
    @IBOutlet weak var icon: UIImageView!
    @IBOutlet weak var nameLabel: UILabel!
    @IBOutlet weak var speedLabel: UILabel!
    @IBOutlet weak var totalLabel: UILabel!
    @IBOutlet weak var progressLabel: UILabel!
    @IBOutlet weak var downloadButton: UIButton!
    
    var model = CXDownloadModel()
    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
    }
    
    private var state: CXDownloadState = .default {
        didSet {
            adaptDownloadButtonStyle(with: state)
        }
    }
    
//    private var url: String?
//    private var vid: String = ""
//    private var fileName: String = ""
    private var progress: Float = 0
    override func awakeFromNib() {
        super.awakeFromNib()
        downloadButton.addTarget(self, action: #selector(onDownloadClick(_:)), for: .touchUpInside)

    }
    func bind(_ data: CXDownloadModel) {
        self.model = data
        nameLabel.text = model.fileName
        speedLabel.text = ""
        progressLabel.text = ""
        totalLabel.text = ""
        progress = model.progress
        self.progressView.progress = model.progress
        reloadLabelWithModel(data)
    }
    
    
    func bindUploadData(_ data: MYGUploadModel) {
        nameLabel.text = data.name
        speedLabel.text = ""
        progressLabel.text = ""
        totalLabel.text = ""
        progress = Float(data.progress) ?? 0.0
        self.progressView.progress = Float(data.progress) ?? 0.0
    }
    func updateDownloadState(_ state: CXDownloadState) {
        self.state = state
    }
    
    func adaptDownloadButtonStyle(with state: CXDownloadState) {
        var image: UIImage?
        switch state {
         
        case .`default`:
            image = UIImage(named: "MYG_cloudDisk_Download")
        case .downloading:
            self.statusLB.text = ""
            image = UIImage(named: "MYG_cloudDisk_pause")
            break
        case .waiting:
            self.statusLB.text = ""
            image = UIImage(named: "MYG_cloudDisk_wait")
            break
        case .paused:
            self.statusLB.text = "下载已暂停"
            image = UIImage(named: "MYG_cloudDisk_Download")
            break
        case .finish:
            image = UIImage(named: "MYG_cloudDisk_Download")
            self.statusLB.text = "已下载至文件夹"
            break
        case .cancelled, .error:
            image = UIImage(named: "MYG_cloudDisk_Download")
            self.statusLB.text = ""
            break
        }
        downloadButton.setImage(image, for: .normal)
        if state == .downloading {
            progressLabel.text = "\(Int(progress * 100))%"
            progressView.progress = progress
        } else {
            progressLabel.text = ""
//            downloadButton.layer.cornerRadius = 0
//            downloadButton.layer.borderWidth = 0
        }
    }
    
    func reloadLabelWithModel(_ data: CXDownloadModel) {
        // Resolve reusable cell.
        if model.url != data.url { return }
        
        progress = model.progress
        updateDownloadState(model.state)
        
        let totalSize = CXDToolbox.string(fromByteCount: model.totalFileSize)
        let tmpSize = CXDToolbox.string(fromByteCount: model.tmpFileSize)
        if model.state == .finish {
            totalLabel.text = totalSize
        } else {
            if model.tmpFileSize > 0 && model.totalFileSize > 0 {
                totalLabel.text = "\(tmpSize) / \(totalSize)"
            } else {
                totalLabel.text = ""
            }
        }
        
//        if model.speed > 0 {
//            speedLabel.text = CXDToolbox.string(fromByteCount: model.speed) + " / s"
//        }
//        speedLabel.isHidden = !(model.state == .downloading && model.totalFileSize > 0)
    }
    
    @objc func progressLabelDidTap() {
        onDownloadClick(downloadButton)
    }
    
    func startDownload() {
        self.onDownloadClick(downloadButton)
    }
    
    @objc func onDownloadClick(_ sender: UIButton) {
        guard let url = self.model.url else { return }
        let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory,
                                                        .userDomainMask, true)
        let documentsDirectory = paths.last!
        let path = documentsDirectory + "/" + (self.model.fileName ?? "")

//        let image = UIImage.init(named: "myCloud_docoument")
//        let data = image!.jpegData(compressionQuality: 0.001)
//
//        do {
//            try data?.write(to: URL(fileURLWithPath: path))
//        } catch {
//            print("用户数据保存失败")
//        }
        if state == .default || state == .cancelled || state == .paused || state == .error {
            CXDownloadManager.shared.download(url: url, toDirectory: path, fileName: self.model.fileName)
        } else if state == .downloading || state == .waiting {
            CXDownloadManager.shared.pause(url: url)
        }
    }
    
}
